<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/10/25
 * Time: 11:01
 */

namespace app\api\controller;


use app\common\controller\Base;
use app\common\lib\filters\WordFilter;
use app\common\model\ApiResponse;
use app\common\model\Topic;
use app\common\model\TopicChat;
use app\common\model\TopicEssay;
use app\common\utils\DateTimeUtil;
use think\Cache;
use think\Db;
use think\db\Query;

class Topics extends Base
{
    /**
     * 老师下面的话题列表
     *
     * @return ApiResponse
     */
    public function list_topic() {
        $form = $this->getAndCheckForm([
            ['teacher_id','require|integer','老师id不能为空|无效的id值'],
            ['page','integer','无效的页码'],
            ['rows','integer',],
        ]);
        $rows = $form['rows']??10;
        $page = $form['page']??1;
        $teacherId = $form['teacher_id'];

        $uid = checkUserToken();

        $re = Topic::apiList($teacherId, $rows, $page, $uid, $this->isPC());

        return ApiResponse::success($re['list'], $re['total']??null, $rows);
    }

    /**
     * topic
     * 获取单条话题详情数据
     *
     * @author zhengkai
     * @date 20180628
     *
     * @return ApiResponse
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function topic()
    {
        $uid = checkUserToken(false);

        $form = $this->getAndCheckForm([
            ['topic_id','require|integer','话题id不能为空|无效的id值'],
        ]);

        $likedSQL = $uid>0 ? ",exists(select * from user_topic_liked l where l.topic_id=topic.id and l.uid=$uid) have_liked" : '';

        $query = Db::table('topic')
            ->where('topic.id','=', $form['topic_id'])
            ->field('topic.*' . $likedSQL)
            ->find();
        $today = date('Y-m-d');
        $query['is_close'] = ($today !== $query['play_date']);
        return ApiResponse::success($query);
    }

    /**
     * 给话题点赞
     *
     * @return ApiResponse
     */
    public function gave_liked_to_topic() {
        $form = $this->getAndCheckForm([
            ['topic_id', 'require|integer',],
            ['cancel', 'integer',],
        ]);

        $uid = checkUserToken(true);

        $re = Topic::gaveLike($uid, $form['topic_id'], empty($form['cancel']));

        if ($re) return ApiResponse::success();
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED);
    }

    /**
     * 话题下的图文动态
     *
     * @return ApiResponse
     */
    public function list_essay() {
        $form = $this->getAndCheckForm([
            ['topic_id','require|integer',],
            ['page','integer','无效的页码'],
            ['rows','integer',],
        ]);

        $query = Db::table('topic_essay');
        $query->where('topic_id','=',$form['topic_id']);
        $query->order('id','desc');
        if ($this->isPC()) {
            $result = $query->paginate($form['rows']??10,false,['page'=>$form['page']??1]);
            $list = $result->items();
            self::timeFormatList($list,'created');
            $total = $result->total();
            return ApiResponse::success($list, $total,$form['rows']??10);
        } else {
            $list = $query->page($form['page']??1,$form['rows']??10)->select();
            self::timeFormatList($list,'created');
            return ApiResponse::success($list);
        }
    }


    /**
     * content_list
     * 单个图文直播话题的图文列表
     * @api POST http://xxx/api/topics/content_list
     *      topic_id 必填 直播话题id
     *      page 选填 当前页数，默认1
     *      limit 选填 每页获取条数，默认10
     *
     * @author zhengkai
     * @date 2018-05-08
     *
     * @return ApiResponse
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function content_list()
    {
        $uid = checkUserToken(false);

        $form = $this->getAndCheckForm([
            ['topic_id','require|integer', '直播话题id不能为空|参数类型错误'],
            ['page','integer', '参数类型错误'],
            ['limit','integer', '参数类型错误'],
        ]);

        if (!isset($form['page'])) $form['page'] = 1;
        if (!isset($form['limit'])) $form['limit'] = 10;

        $topic = Db::table('topic')
            ->alias('tc')
            ->join('teacher t', 'tc.teacher_id=t.id', 'left')
            ->where('tc.id', $form['topic_id'])
            ->field('tc.id, tc.title, tc.play_date, tc.num_liked, t.realname as teacher_realname')
            ->find();

        if (!$topic) return ApiResponse::success([]);

        $is_like = Db::table('user_topic_liked')->where([
            'uid' => $uid,
            'topic_id' => $form['topic_id']
        ])->count();

        $is_liked = $is_like?1:0;

        $list = Db::table('topic_essay')
            ->where('topic_id', $topic['id'])
            ->order('created desc')
            ->page(($form['page']-1), $form['limit'])
            ->select();
        foreach ($list as &$val) {
            $val['created'] = date('H:i', strtotime($val['created']));
            unset($val['topic_id']);
        }

        $totalNum = Db::table('topic_essay')->where('topic_id', $topic['id'])->count();

        $topic['is_liked'] = $is_liked;
        $topic['list'] = $list;
        $topic['page_total'] = ceil($totalNum/intval($form['limit']));
        $data = $topic;


        return ApiResponse::success($data);
    }

    /**
     * 话题下的互动列表
     *
     * @return ApiResponse
     */
    public function list_chat() {
        $form = $this->getAndCheckForm([
            ['topic_id','require|integer',],
            ['page','integer','无效的页码'],
            ['rows','integer',],
        ]);

        $re = TopicChat::list($form['topic_id'],$form['rows']??10,$form['page']??1, $this->isPC());

        if ($this->isPC()) return ApiResponse::success($re['data'], $re['total'], $form['rows']??10);
        else return ApiResponse::success($re);
    }

    /**
     * 提交互动内容，输入reply_id表示回复，否则是新发表
     * 要求登录
     *
     * @return ApiResponse
     */
    public function submit_chat() {
        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['topic_id','integer','话题id无效类型',],
            ['reply_id','integer','回复id无效类型',],
            ['content','require',],
        ]);
        if (empty($form['topic_id']) && empty($form['reply_id'])) {
            ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'话题id和回复id不能都为空');
        }

        $data = ['user_id' => $uid, 'content' => $form['content']];
        if (empty($form['reply_id'])) {
            // 新发表
            $data['topic_id'] = $form['topic_id'];
        } else {
            // 回复
            $target = TopicChat::get($form['reply_id']);
            if (empty($target)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'回复目标不存在');
            $data['topic_id'] = $target->topic_id;
            $data['reply_target_id'] = $target->id;
        }
        $topic = Topic::get($data['topic_id']);
        if ($topic->play_date !== date('Y-m-d')) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'话题已过期关闭');
        }

        Db::transaction(function()use ($data,$uid,$topic){
            $model = TopicChat::create($data);
            if (TopicChat::checkUser($topic->id, $uid)) Topic::increaseUserCount($model->topic_id);
        });

        return ApiResponse::success();
    }

    /**
     * 格式化列表里的时间
     * @param array $list
     * @param array ...$fields
     */
    private static function timeFormatList(array & $list, ...$fields) {
        foreach ($list as & $item) {
            foreach ($fields as $field) {
                $item[$field] = DateTimeUtil::format($item[$field]);
            }
        }
    }

    /**
     * pc_index
     * web pc首页图文直播数据
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return false|static[]
     * @throws \think\exception\DbException
     */
    public static function pc_index($teacher_id='')
    {
        $result = \app\api\model\topic\TopicEssay::getWeekList($teacher_id);

        return $result;
    }
}